<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;

class FlowController extends AdminController
{
    protected string $table = 'flows';

    protected string $model = "flow";

    protected array $user_type = [
        1=>"指定人",
        2=>"直接主管",
        3=>"指定角色"
    ];

    #[NoReturn] public function init(): void
    {
        $this->routeWhiteLst = ['flow@getoptions','flow@flowuserform'];
        parent::init();
    }

    /**
     * 获取列表页数据
     * @return void
     */
    #[NoReturn] public function indexAction(): void
    {
        try {
            if (Request::input("is_hid") !== null) {
                $this->where[] = ['is_hid','=',Request::input("is_hid")];
            }
            $sql = FlowModel::query()
                ->when($this->includes,function ($query,$value) {
                    $query->with($value);
                })
                ->where($this->where)
                ->when($this->whereIn,function ($query,$value){
                    foreach ($value as $item) {
                        $query->whereIn($item[0], $item[1]);
                    }
                });
            $sql->when(Request::input("sort"),function ($query,$value){
                $query->orderBy("id",match ($value)
                {
                    "-id"=>'asc',
                    default => 'desc',
                });
            });
            $data = $sql->paginate(Request::input("limit",10),['*'],NULL,Request::input("p",1));
            $_data = collect($data->items())->toArray();
            $approvals = dictByName('approvals');
            foreach ($_data as $key=>$vo) {
                $_data[$key]['category_name'] = $approvals[$vo['category_id']];
            }
            $result = [
                'items' => $_data,
                'total'=>$data->total(),
                'per_page' => $data->perPage(),
                'page' => $data->currentPage()
            ];
            $this->apiSuccess($result,"获取成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    #[NoReturn] public function getOptionsAction(): void
    {
        $data = dict('approvals');
        $result = [];
        foreach ($data as $key=>$vo) {
            $result[] = [
                'value'=>(int)$vo,
                'label'=>$key
            ];
        }
        $this->apiSuccess($result,"获取成功",20000);
    }

    /**
     * 设置流程用户
     * @return void
     */
    #[NoReturn] public function flowUserAction(): void
    {
        try {
            $flow = FlowModel::query()->where("id",Request::input("flow_id"))->first();
            if ($flow) {
                $data = Request::input("data");
                $json = [];
                $user_id = [];
                $position_id = [];
                $role_id = [];
                foreach ($data as $vo) {
                    foreach ($vo['user_ids'] as $item) {
                        if ($vo['user_type']==1) {
                            $user_id[] = $item;
                        }elseif ($vo['user_type']==2) {
                            $position_id[] = $item;
                        }else {
                            $role_id[] = $item;
                        }
                    }
                }
                $orgUser = [];
                if ($user_id) {
                    $orgUser = OrganizationUserModel::query()
                        ->whereIn("user_id", $user_id)
                        ->get()->keyBy("user_id")->toArray();
                }
                $position = [];
                if ($position_id) {
                    $position = UserModel::query()
                        ->join("organization_users", "users.id","=", "organization_users.user_id")
                        ->whereIn("position_id", $position_id)
                        ->selectRaw("position_id,user_id,organization_id")
                        ->get()->toArray();
                }
                $role = [];
                if ($role_id) {
                    $role = UserHasRoleModel::query()->whereIn("role_id", $role_id)
                        ->join("organization_users", "user_has_roles.user_id", "=","organization_users.user_id")
                        ->selectRaw("role_id,user_id,organization_id")
                        ->get()->toArray();
                }
                foreach ($data as $key => $vo) {
                    $users = [];
                    if ($vo['user_type']==1) {
                        foreach ($vo['user_ids'] as $ignored) {
                            $users[] = [
                                "org_id" => $orgUser[$ignored]['organization_id'],
                                "user_id" => $ignored,
                                "position" => ""
                            ];
                        }
                    }elseif ($vo['user_type']==2) {
                        foreach ($position as $item) {
                            $users[] = [
                                "org_id" => $item['organization_id'],
                                "user_id" => $item['user_id'],
                                "position" => ""
                            ];
                        }
                    }else {
                        foreach ($role as $item) {
                            $users[] = [
                                "org_id" => $item['organization_id'],
                                "user_id" => $item['user_id'],
                                "position" => ""
                            ];
                        }
                    }
                    $json[] = [
                        "type" => $vo['type'],
                        "level" => $key + 1,
                        'user' => $users,
                        'mode' => $vo['approval_type'] ?? 1,
                        'user_type' => $vo['user_type'],
                        "user_type_title" => $this->user_type[$vo['user_type']]
                    ];
                }
                FlowModel::where("id", $flow['id'])->update([
                    'data' => json_encode([
                        'title' => "审批流程",
                        'type' => 2,
                        'flow' => $json
                    ]),
                    'original_data'=>$data
                ]);
                $this->apiSuccess([], '保存成功', 20000);
            }else {
                $this->apiError("数据不存在");
            }
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    #[NoReturn] public function flowUserFormAction(): void
    {
        try {
            $flow = FlowModel::query()->where("id",Request::input("ids"))->first();
            if ($flow) {
                $result = [];
                if ($flow['data']) {
                    $data = $flow['data']['flow'];
                    $original_data = $flow['original_data'];
                    $user_id = [];
                    foreach ($data as $vo) {
                        foreach ($vo['user'] as $item) {
                            if ($vo['user_type']==1) {
                                $user_id[] = $item['user_id'];
                            }
                        }
                    }
                    $users = OrganizationUserModel::query()
                        ->join("users","users.id","=","organization_users.user_id")
                        ->whereIn("user_id", $user_id)->get()->keyBy("id")->toArray();
//                    $users = UserModel::query()->whereIn("id", $user_id)->get()->keyBy("id")->toArray();
                    foreach ($data as $key=>$vo) {
                        $t = [
                            'type' => $vo['type'],
                            'label' => $vo['user_type_title'] ?? "设置",
                            'user_type' => $vo['user_type'] ?? 1,
                            'approval_type' => $vo['mode'] ?? 1,
                        ];
                        if ($vo['user_type']==1) {
                            foreach ($vo['user'] as $item) {
                                $t['users'][] = $users[$item['user_id']];
                                $t['user_ids'][] = $item['user_id'];
                            }
                        }else {
                            $t['users'] = [];
                            $t['user_ids'] = $original_data[$key]['user_ids'];
                        }
                        if ($vo['type'] == 1) {
                            $t['title'] = "审批人";
                            $result['stampLst'][] = $t;
                        } else {
                            $t['title'] = "抄送人";
                            $result['promotionLst'][] = $t;
                        }
                    }
                }else {
                    $result['stampLst'] = [];
                    $result['promotionLst'] = [];
                }
                $this->apiSuccess($result,"获取成功",20000);
            }else {
                $this->apiError("数据不存在");
            }
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
